package DB;

import java.sql.*;
import java.util.ArrayList;
import java.util.List;

public class GradeUtil {
    public static List<Answer> showGrade(String userName) throws SQLException {
        List<Answer> answers=new ArrayList<>();
        String sql="select *\n" +
                "from historyGrade where userName=?";
        Connection connection=JDBC.getConnection();
        PreparedStatement preparedStatement=connection.prepareStatement(sql);
        preparedStatement.setString(1,userName);
        ResultSet resultSet = preparedStatement.executeQuery();
        while (resultSet.next()){
            Answer answer=new Answer();
            answer.setAnswerId(resultSet.getInt("answerId"));
            answer.setUserName(resultSet.getString("userName"));
            answer.setGrade(resultSet.getInt("grade"));
            answer.setCorrect(resultSet.getInt("correct"));
            answer.setWrong(resultSet.getInt("wrong"));
            answer.setTime(resultSet.getInt("time"));
            answers.add(answer);
        }
        resultSet.close();
        preparedStatement.close();
        JDBC.close(connection);
        return answers;
    }
    public static int addAnswer(String userName,int grade,int correct,int wrong,int time) throws SQLException {
        String sql= "insert into historyGrade\n" +
                "(userName,grade, correct, wrong, time)\n" +
                "values \n" +
                "    (?,?,?,?,?)";
        Connection connection=JDBC.getConnection();
        PreparedStatement preparedStatement=connection.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);
        preparedStatement.setString(1,userName);
        preparedStatement.setInt(2,grade);
        preparedStatement.setInt(3,correct);
        preparedStatement.setInt(4,wrong);
        preparedStatement.setInt(5,time);
        int a=preparedStatement.executeUpdate();
        System.out.println(a);
        ResultSet result=preparedStatement.getGeneratedKeys();
        int id=0;
        if(result.next()) {
            id = result.getInt(1);
        }
        result.close();
        preparedStatement.close();
        JDBC.close(connection);
        System.out.println("id="+id);
        return id;
    }
}
